<template>
  <div class="district-analysis-page">
    <a-row :gutter="16">
      <a-col :span="24">
        <a-card title="区域房价分析" :bordered="false">
          <a-form layout="inline">
            <a-form-item label="选择城市">
              <a-select
                v-model:value="selectedCity"
                style="width: 120px"
                placeholder="选择城市"
                @change="handleCityChange"
              >
                <a-select-option v-for="city in cities" :key="city" :value="city">
                  {{ city }}
                </a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item>
              <a-button type="primary" @click="fetchDistrictData" :loading="loading">
                分析
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px" v-if="selectedCity">
      <a-col :span="12">
        <a-card :bordered="false" title="区域房源数量分布">
          <div ref="districtCountChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card :bordered="false" title="区域均价排名">
          <div ref="districtPriceChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px" v-if="selectedCity">
      <a-col :span="24">
        <a-card :bordered="false" title="区域房价数据表">
          <a-table
            :dataSource="districtData"
            :columns="districtColumns"
            :pagination="false"
            :loading="loading"
            rowKey="district"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'avgPrice' || column.dataIndex === 'medianPrice'">
                <span :style="{ color: '#f5222d', fontWeight: 'bold' }">{{ record[column.dataIndex] }} 万元</span>
              </template>
              
              <template v-if="column.dataIndex === 'avgUnitPrice'">
                <span :style="{ color: '#f5222d', fontWeight: 'bold' }">{{ record[column.dataIndex] }} 万元/㎡</span>
              </template>
              
              <template v-if="column.dataIndex === 'action'">
                <a-button type="link" @click="showDistrictDetail(record)">
                  查看详情
                </a-button>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
    
    <!-- 区域详情抽屉 -->
    <a-drawer
      :title="`${selectedDistrict.district} 区域详情`"
      :visible="drawerVisible"
      :width="720"
      @close="closeDrawer"
      placement="right"
    >
      <a-row :gutter="16">
        <a-col :span="6">
          <a-statistic
            title="房源数量"
            :value="selectedDistrict.houseCount"
          >
            <template #suffix>
              <home-outlined />
            </template>
          </a-statistic>
        </a-col>
        <a-col :span="6">
          <a-statistic
            title="平均总价"
            :value="selectedDistrict.avgPrice"
            :precision="2"
            suffix="万元"
          >
            <template #prefix>
              <money-collect-outlined />
            </template>
          </a-statistic>
        </a-col>
        <a-col :span="6">
          <a-statistic
            title="中位数总价"
            :value="selectedDistrict.medianPrice"
            :precision="2"
            suffix="万元"
          >
            <template #prefix>
              <dollar-outlined />
            </template>
          </a-statistic>
        </a-col>
        <a-col :span="6">
          <a-statistic
            title="平均单价"
            :value="selectedDistrict.avgUnitPrice"
            :precision="2"
            suffix="万元/㎡"
          >
            <template #prefix>
              <rise-outlined />
            </template>
          </a-statistic>
        </a-col>
      </a-row>
      
      <a-divider />
      
      <a-row :gutter="16">
        <a-col :span="12">
          <a-card title="价格分布" :bordered="false">
            <div ref="districtPriceDistChartRef" style="width: 100%; height: 300px"></div>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card title="面积分布" :bordered="false">
            <div ref="districtAreaDistChartRef" style="width: 100%; height: 300px"></div>
          </a-card>
        </a-col>
      </a-row>
      
      <a-row :gutter="16" style="margin-top: 16px">
        <a-col :span="12">
          <a-card title="户型分布" :bordered="false">
            <div ref="districtLayoutChartRef" style="width: 100%; height: 300px"></div>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card title="装修分布" :bordered="false">
            <div ref="districtDecorationChartRef" style="width: 100%; height: 300px"></div>
          </a-card>
        </a-col>
      </a-row>
      
      <a-divider />
      
      <a-button type="primary" @click="viewDistrictHouses">
        查看该区域房源
      </a-button>
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useHouseStore } from '../stores/houseStore'
import { useAnalysisStore } from '../stores/analysisStore'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'
import {
  HomeOutlined,
  MoneyCollectOutlined,
  RiseOutlined,
  DollarOutlined
} from '@ant-design/icons-vue'

const router = useRouter()
const houseStore = useHouseStore()
const analysisStore = useAnalysisStore()

// 状态
const loading = ref(false)
const selectedCity = ref('')
const cities = ref([])
const districtData = ref([])
const drawerVisible = ref(false)
const selectedDistrict = ref({})

// 图表引用
const districtCountChartRef = ref(null)
const districtPriceChartRef = ref(null)
const districtPriceDistChartRef = ref(null)
const districtAreaDistChartRef = ref(null)
const districtLayoutChartRef = ref(null)
const districtDecorationChartRef = ref(null)

// 图表实例
let districtCountChart = null
let districtPriceChart = null
let districtPriceDistChart = null
let districtAreaDistChart = null
let districtLayoutChart = null
let districtDecorationChart = null

// 表格列定义
const districtColumns = [
  {
    title: '区域',
    dataIndex: 'district',
    key: 'district',
    width: 120,
    fixed: 'left'
  },
  {
    title: '房源数量',
    dataIndex: 'houseCount',
    key: 'houseCount',
    width: 120,
    sorter: (a, b) => a.houseCount - b.houseCount
  },
  {
    title: '平均总价(万元)',
    dataIndex: 'avgPrice',
    key: 'avgPrice',
    width: 150,
    sorter: (a, b) => a.avgPrice - b.avgPrice
  },
  {
    title: '中位数总价(万元)',
    dataIndex: 'medianPrice',
    key: 'medianPrice',
    width: 150,
    sorter: (a, b) => a.medianPrice - b.medianPrice
  },
  {
    title: '平均单价(万元/㎡)',
    dataIndex: 'avgUnitPrice',
    key: 'avgUnitPrice',
    width: 180,
    sorter: (a, b) => a.avgUnitPrice - b.avgUnitPrice
  },
  {
    title: '平均面积(㎡)',
    dataIndex: 'avgArea',
    key: 'avgArea',
    width: 120,
    sorter: (a, b) => a.avgArea - b.avgArea
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 100,
    fixed: 'right'
  }
]

// 处理城市变化
const handleCityChange = (value) => {
  selectedCity.value = value
  fetchDistrictData()
}

// 获取区域数据
const fetchDistrictData = async () => {
  if (!selectedCity.value) {
    message.warning('请选择城市')
    return
  }
  
  loading.value = true
  
  try {
    // 获取区域分析数据
    const data = await analysisStore.fetchDistrictAnalysis(selectedCity.value)
    
    // 处理数据，保留两位小数
    districtData.value = data.map(item => ({
      ...item,
      avgPrice: parseFloat(item.avgPrice.toFixed(2)),
      medianPrice: parseFloat(item.medianPrice.toFixed(2)),
      avgUnitPrice: parseFloat(item.avgUnitPrice.toFixed(2)),
      avgArea: parseFloat(item.avgArea.toFixed(1))
    }))
    
    // 更新图表
    nextTick(() => {
      initDistrictCountChart()
      initDistrictPriceChart()
    })
  } catch (error) {
    console.error('获取区域分析数据失败:', error)
    message.error('获取区域分析数据失败')
  } finally {
    loading.value = false
  }
}

// 初始化区域房源数量分布图表
const initDistrictCountChart = () => {
  if (!districtCountChartRef.value) return
  
  districtCountChart = echarts.init(districtCountChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: districtData.value.map(item => item.district)
    },
    series: [
      {
        name: '房源数量',
        type: 'pie',
        radius: ['45%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: districtData.value.map(item => ({
          value: item.houseCount,
          name: item.district
        }))
      }
    ]
  }
  
  districtCountChart.setOption(option)
}

// 初始化区域均价排名图表
const initDistrictPriceChart = () => {
  if (!districtPriceChartRef.value) return
  
  districtPriceChart = echarts.init(districtPriceChartRef.value)
  
  // 按均价排序
  const sortedData = [...districtData.value].sort((a, b) => b.avgUnitPrice - a.avgUnitPrice)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '均价(万元/㎡)'
    },
    yAxis: {
      type: 'category',
      data: sortedData.map(item => item.district),
      axisLabel: {
        interval: 0
      }
    },
    series: [
      {
        name: '均价',
        type: 'bar',
        data: sortedData.map(item => item.avgUnitPrice),
        itemStyle: {
          color: function(params) {
            // 颜色渐变
            const colorList = ['#f5222d', '#fa8c16', '#faad14', '#a0d911', '#52c41a']
            return colorList[Math.min(params.dataIndex, colorList.length - 1)]
          }
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c} 万/㎡'
        }
      }
    ]
  }
  
  districtPriceChart.setOption(option)
}

// 显示区域详情
const showDistrictDetail = async (district) => {
  selectedDistrict.value = district
  drawerVisible.value = true
  
  try {
    // 获取区域详细分析数据
    const detailData = await analysisStore.fetchDistrictDetail(selectedCity.value, district.district)
    
    // 更新区域详情数据
    Object.assign(selectedDistrict.value, detailData)
    
    // 更新图表
    nextTick(() => {
      initDistrictDetailCharts(detailData)
    })
  } catch (error) {
    console.error('获取区域详情数据失败:', error)
    message.error('获取区域详情数据失败')
  }
}

// 初始化区域详情图表
const initDistrictDetailCharts = (detailData) => {
  // 价格分布图表
  if (districtPriceDistChartRef.value) {
    districtPriceDistChart = echarts.init(districtPriceDistChartRef.value)
    
    const priceRanges = Object.keys(detailData.priceDistribution)
    const priceValues = priceRanges.map(range => detailData.priceDistribution[range])
    
    const priceOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: priceRanges,
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '房源数量'
      },
      series: [
        {
          name: '价格分布',
          type: 'bar',
          data: priceValues,
          itemStyle: {
            color: '#1890ff'
          }
        }
      ]
    }
    
    districtPriceDistChart.setOption(priceOption)
  }
  
  // 面积分布图表
  if (districtAreaDistChartRef.value) {
    districtAreaDistChart = echarts.init(districtAreaDistChartRef.value)
    
    const areaRanges = Object.keys(detailData.areaDistribution)
    const areaValues = areaRanges.map(range => detailData.areaDistribution[range])
    
    const areaOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: areaRanges,
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '房源数量'
      },
      series: [
        {
          name: '面积分布',
          type: 'bar',
          data: areaValues,
          itemStyle: {
            color: '#13c2c2'
          }
        }
      ]
    }
    
    districtAreaDistChart.setOption(areaOption)
  }
  
  // 户型分布图表
  if (districtLayoutChartRef.value) {
    districtLayoutChart = echarts.init(districtLayoutChartRef.value)
    
    const layouts = Object.keys(detailData.layoutDistribution)
    const layoutValues = layouts.map(layout => detailData.layoutDistribution[layout])
    
    const layoutOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: layouts
      },
      series: [
        {
          name: '户型分布',
          type: 'pie',
          radius: '60%',
          data: layouts.map((layout, index) => ({
            value: layoutValues[index],
            name: layout
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    districtLayoutChart.setOption(layoutOption)
  }
  
  // 装修分布图表
  if (districtDecorationChartRef.value) {
    districtDecorationChart = echarts.init(districtDecorationChartRef.value)
    
    const decorations = Object.keys(detailData.decorationDistribution)
    const decorationValues = decorations.map(decoration => detailData.decorationDistribution[decoration])
    
    const decorationOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: decorations
      },
      series: [
        {
          name: '装修分布',
          type: 'pie',
          radius: '60%',
          data: decorations.map((decoration, index) => ({
            value: decorationValues[index],
            name: decoration
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    districtDecorationChart.setOption(decorationOption)
  }
}

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false
}

// 查看区域房源
const viewDistrictHouses = () => {
  router.push({
    path: '/search',
    query: {
      city: selectedCity.value,
      district: selectedDistrict.value.district
    }
  })
}

// 监听窗口大小变化，重绘图表
window.addEventListener('resize', () => {
  districtCountChart?.resize()
  districtPriceChart?.resize()
  districtPriceDistChart?.resize()
  districtAreaDistChart?.resize()
  districtLayoutChart?.resize()
  districtDecorationChart?.resize()
})

// 页面加载时获取数据
onMounted(async () => {
  try {
    // 获取城市列表
    const citiesList = await houseStore.fetchCities()
    cities.value = citiesList
    
    // 默认选择第一个城市
    if (cities.value.length > 0) {
      selectedCity.value = cities.value[0]
      await fetchDistrictData()
    }
  } catch (error) {
    console.error('获取城市列表失败:', error)
    message.error('获取城市列表失败')
  }
})
</script>

<style scoped lang="scss">
.district-analysis-page {
  padding: 24px;
}
</style> 